<template>
  <div class="user-list-container">
    <!-- 查询表单 -->
    <!-- <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" label-width="80px">
        <el-row :gutter="20">
           <el-col :span="6">
            <el-form-item label="合作单位" prop="username">
              <companySelect />
            </el-form-item>
          </el-col> 
          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.insuranceEffectiveStatus"
                placeholder="请选择状态"
                clearable
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: right">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card> -->

    <!-- 表格 -->
    <el-card shadow="never" class="table-card">
      <div style="display: flex; margin-bottom: 20px">
        <el-button type="primary" @click="openAddDialog">创建</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column prop="course_id" label="ID" width="80" />
        <!-- <el-table-column prop="commercial_insurance_name" label="保险名称" /> -->
        <el-table-column prop="course_name" label="课程名称" />
        <el-table-column prop="course_current_price" label="价格" />
        <el-table-column prop="buy_number" label="销量" />
        <el-table-column prop="teacher_name" label="讲师名称" />

        <el-table-column prop="created_at" label="创建时间" />
        <el-table-column label="课程时间" width="180">
          <template #default="scope">
            {{ scope.row.course_start_at }}-{{ scope.row.course_end_at }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button link @click="handleTableOption('edit', scope.row)"
              >编辑</el-button
            >
            <el-button link type="primary" @click="openClass(scope.row.course_id)">查看课时</el-button>
            <el-button link type="primary" @click="openClassuser(scope.row.course_id)">查看报名用户</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)"
              >删除</el-button
            >
            <!-- <el-button link type="primary">设置为首页banner图推荐</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </el-card>
    <el-dialog
    v-if="dialogVisible"
      v-model="dialogVisible"
      title="课程"
      width="800"
      :before-close="handleCloseAddDialog"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="150px"
        class="demo-form"
      >
        <!-- 公司ID -->
        <el-form-item label="课程名称" prop="course_name">
          <el-input v-model="form.course_name" />
        </el-form-item>
        <el-form-item label="课程时间" prop="course_end_at">
          <el-date-picker
            v-model="classTime"
            type="daterange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
            @change="timercChange"
          />
        </el-form-item>

        <el-form-item label="课程活动" prop="course_cate_id">
          <el-select
            v-model="form.course_cate_id"
            placeholder="请选择课程活动"
            filterable
          >
            <el-option
              v-for="item in typeList"
              :key="item.course_cate_id"
              :label="item.course_cate_name"
              :value="item.course_cate_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程标签" prop="tag_id_str">
          <el-select
            v-model="form.tag_id_str"
            placeholder="请选择课程标签"
            multiple
            filterable
          >
            <el-option
              v-for="item in tagList"
              :key="item.tag_id"
              :label="item.tag_name"
              :value="item.tag_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="讲课老师" prop="tag_id_str">
          <el-select
            v-model="form.teacher_id"
            placeholder="请选择老师"
            filterable
          >
            <el-option
              v-for="item in teacherLlist"
              :key="item.teacher_id"
              :label="item.teacher_name"
              :value="item.teacher_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文字介绍" prop="course_outline">
          <rich-txt
            :modelValue="form.course_outline"
            @change="
              (val) => {
                form.course_outline = val;
              }
            "
          ></rich-txt>
        </el-form-item>
        <el-form-item label="购买次数" prop="buy_number">
          <el-input type="number" v-model="form.buy_number" />
        </el-form-item>
        <!-- <el-form-item label="购买课程节数" prop="course_number">
          <el-input type="number" v-model="form.course_number" />
        </el-form-item> -->
        <el-form-item label="课程评分 (1-5)" prop="course_score">
          <el-input type="number" v-model="form.course_score" />
        </el-form-item>
        <el-form-item label="课程原价" prop="course_original_price">
          <el-input type="number" v-model="form.course_original_price" />
        </el-form-item>
        <el-form-item label="课程现价" prop="course_current_price">
          <el-input type="number" v-model="form.course_current_price" />
        </el-form-item>
        <el-form-item label="是否推荐" prop="is_recommend">
          <el-switch
            v-model="form.is_recommend"
            :active-value="1"
            :inactive-value="0"
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAddDialog">取消</el-button>
          <el-button type="primary" @click="submitForm">
            {{ dialogType == "edit" ? "修改" : "创建" }}
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog 
      v-model="dialogVisibleclass" 
      v-if="dialogVisibleclass"
      title="课程课时">
    <classTable :classId="classId"></classTable>
    </el-dialog>
    <el-dialog 
      v-model="dialogVisibleclass2" 
      v-if="dialogVisibleclass2"
      title="报名用户">
    </el-dialog>
  </div>
</template>

<script>
import tableMixin from "@/mixins/tableMixin";
import api from "@/request/api.js";
import upload from "@/components/upload.vue";
import richTxt from "@/components/richTxt.vue";
import classTable from "./compontent/classTable3.vue";

export default {
  name: "UserList",
  mixins: [tableMixin],
  components: { upload, richTxt ,classTable},
  data() {
    // 结束日期验证
    const validateEndDate = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请选择结束日期"));
      }
      if (
        this.form.start_at &&
        new Date(value) < new Date(this.form.start_at)
      ) {
        return callback(new Error("结束日期不能早于开始日期"));
      }
      callback();
    };

    return {
      classId:'',
      typeList: [],
      tagList: [],
      teacherLlist: [],
      companyChildList: {},
      //查询参数
      queryParams: { insuranceEffectiveStatus: "" },
      apimodel: "classaa",
      apival: "getList",
      // 状态选项
      statusOptions: [
        { value: -1, label: "全部" },
        { value: 1, label: "生效/上架" },
        { value: 2, label: "不生效/下架" },
        { value: 0, label: "预留" },
      ],
      //创建修改弹窗
      dialogVisible: false,
      dialogVisibleclass: false,
      dialogType: "",
      classTime: "",
      form: {
        course_name: "",
        course_start_at: "",
        course_end_at: "",
        course_cate_id: "",
        tag_id_str: [],
        course_outline: "",
        buy_number: 0,
        course_number: 0,
        course_score: 0,
        course_original_price: 0,
        course_current_price: 0,
        is_recommend: 0,
        teacher_id: "",
      },
      rules: {
        course_name: [
          { required: true, message: "请输入名称", trigger: "change" },
        ],
        course_end_at: [
          { required: true, message: "请选择课程时间", trigger: "change" },
        ],
        course_cate_id: [
          { required: true, message: "请选择课程分类", trigger: "change" },
        ],
        tag_id_str: [
          { required: true, message: "请选择课程标签", trigger: "change" },
        ],
        buy_number: [
          { required: true, message: "请选填写购买人数", trigger: "change" },
        ],
        course_number: [
          { required: true, message: "请选填写课程课节", trigger: "change" },
        ],
        course_outline: [
          { required: true, message: "请选填写文字介绍", trigger: "change" },
        ],
        course_score: [
          { required: true, message: "请选填写课程评分", trigger: "change" },
        ],
        course_original_price: [
          { required: true, message: "请选填写课程原价", trigger: "change" },
        ],
        course_current_price: [
          { required: true, message: "请选填写课程现价", trigger: "change" },
        ],
        course_current_price: [
          { required: true, message: "请选填写课程现价", trigger: "change" },
        ],

        teacher_id: [
          { required: true, message: "请选择讲课老师", trigger: "change" },
        ],
      },
      companys: [],
    };
  },
  mounted() {
    api.tag.getList({ size: 999  ,is_type:1  }).then((res) => {
      if (res.data.code == 200) {
        this.tagList = res.data.content.data;
      }
    });
    api.typeA.getList({ size: 999 }).then((res) => {
      if (res.data.code == 200) {
        this.typeList = res.data.content.data;
      }
    });
    api.teacher.getList({ size: 999 }).then((res) => {
      if (res.data.code == 200) {
        this.teacherLlist = res.data.content.data;
      }
    });
  },
  methods: {
    openClass(id){
      this.classId=id
      this.dialogVisibleclass=true
        
    },
    openClassuser(id){
      this.classId=id
      this.dialogVisibleclass2=true
        
    },
    timercChange(val) {
      this.form.course_start_at = val[0];
      this.form.course_end_at = val[1];
    },
    openAddDialog(option = "") {
      this.dialogVisible = true;
      this.dialogType = option;
    },

    // 加载公司数据

    handleCloseAddDialog() {
      this.dialogVisible = false;
      this.dialogType = "";
      this.form = {
        integral_goods_name: "",
        integral_goods_cover_path: "",
        integral_price: "",
        goods_sales: "",
      };
      this.resetForm();
    },
    // 编辑
    handleTableOption(option, row) {
      if (option == "edit") {
        this.form = row;
        this.form.tag_id_str = [];
        for (let index = 0; index < row.course_tag_list.length; index++) {
          const element = row.course_tag_list[index];
          this.form.tag_id_str.push(element.tag_id);
        }
        this.classTime = [this.form.course_start_at, this.form.course_end_at];
        this.openAddDialog(option);
      }
    },

    // 删除
    handleDelete(row) {
      this.$confirm("确认删除该课程吗?", "提示", {
        type: "warning",
      })
        .then(async () => {
          api.classaa
            .del({
              course_id: row.course_id,
            })
            .then((res) => {
              if (res?.status == 200) {
                this.$message.success("删除成功");
                this.getTableData();
              }
            });
        })
        .catch(() => {});
    },
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const queryObj = this.form;
          queryObj.tag_id_str = this.form.tag_id_str.join(",");
          // 表单验证通过，提交逻辑
          console.log("表单提交:", this.form);
          if (this.dialogType != "edit") {
            api.classaa.create({ ...this.form }).then((res) => {
              if (res?.status == 200) {
                this.$message.success("创建成功");
                this.handleReset();
                this.handleCloseAddDialog();
              }
            });
          } else {
            api.classaa.update({ ...this.form }).then((res) => {
              if (res?.status == 200) {
                this.$message.success("修改成功");
                this.handleReset();
                this.handleCloseAddDialog();
              }
            });
          }
          // 这里可以添加API调用等提交逻辑
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.formRef.resetFields();
    },
    //选择地点
    handleRegionChange(val) {
      this.form.province_id = val.province;
      this.form.city_id = val.city;
      this.form.area_id = val.district;
    },
  },
};
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.table-card {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
